package main

import (
	"context"
	"flag"
	"fmt"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/rest/httpx"
	_ "github.com/zeromicro/zero-contrib/zrpc/registry/consul"
	"mall-backend/api/internal/config"
	"mall-backend/api/internal/handler"
	"mall-backend/api/internal/svc"
	"mall-backend/pkg/errorex"
	"net/http"
)

var configFile = flag.String("f", "etc/api.yaml", "the config file")

func init() {
	//close statis log
	logx.DisableStat()
}

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)

	server := rest.MustNewServer(c.RestConf)
	defer server.Stop()
	httpx.SetErrorHandlerCtx(func(ctx context.Context, err error) (int, any) {
		switch e := err.(type) {
		case *errorex.Error:
			return e.HttpStatus, e.Response()
		default:
			cerr := errorex.NewError(http.StatusInternalServerError, errorex.C_SYSTEM_ERR)
			return cerr.HttpStatus, cerr.Response()
		}
	})
	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx)

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}
